package com.study.sfd.medicine.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.study.common.utils.PageUtils;
import com.study.common.utils.R;
import com.study.sfd.medicine.service.MedicineService;
import com.study.sfd.medicine.vo.MedicineWithImgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * medicine(药品)
 *
 * @author 王个球
 * @email wangdajunzy@163.com
 * @date 2021-11-12 13:37:43
 */
@RestController
@Slf4j
@RequestMapping("medicine/medicine")
public class MedicineController {
  @Autowired
  private MedicineService medicineService;

  /**
   * 列表
   */
  @RequestMapping("/listWithImg")
  public R listWithImg(@RequestParam Map<String, Object> params) {
    PageUtils page = medicineService.queryPageWithImg(params);

    return R.ok().put("page", page);
  }

  /**
   * 列表
   */
  @RequestMapping("/list")
  // @RequiresPermissions("medicine:medicine:list")
  public R list(@RequestParam Map<String, Object> params) {
    PageUtils page = medicineService.queryPage(params);

    return R.ok().put("page", page);
  }


  /**
   * 信息
   */
  @RequestMapping("/info/{id}")
  public R info(@PathVariable("id") Integer id) {
    MedicineWithImgs medicine = medicineService.getDetailById(id);

    // 对象转 json 字符串， 属性名 驼峰 改为 下划线
    SerializeConfig config = new SerializeConfig();
    config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;

    return R.ok().put("medicine", JSON.toJSONString(medicine, config));
  }

  /**
   * 保存
   */
  @RequestMapping("/save")
  // public R save(@ParameterConvert MedicineEntity medicine) { ParameterConvert 转换请求参数
  public R save(@RequestBody String medicine) {
    // System.out.println("medicine s = " + medicine);
    // 对象转 json 字符串，下划线 属性名 改为 驼峰对象属性名
    MedicineWithImgs medicineEntity = JSON.parseObject(medicine, MedicineWithImgs.class);
    // System.out.println("medicineEntity = " + medicineEntity);
    medicineService.saveWithImgs(medicineEntity);

    return R.ok();
  }

  /**
   * 修改
   */
  @PostMapping("/update/{id}")
  public R update(@PathVariable("id") Integer id, @RequestBody String medicineStr) {
    // 对象转 json 字符串，下划线 属性名 改为 驼峰对象属性名
    MedicineWithImgs medicine = JSON.parseObject(medicineStr, MedicineWithImgs.class);
    // System.out.println("medicine = " + medicine);
    medicineService.updateWithImgsById(medicine, id);

    return R.ok();
  }

  /**
   * 删除
   */
  @DeleteMapping("/delete")
  public R delete(@RequestBody Integer[] ids) {
    List<Integer> mdcIds = Arrays.asList(ids);
    log.info("mdcIds = " + mdcIds);
    medicineService.removeWithImgsByIds(mdcIds);

    return R.ok();
  }

}
